import minimist from 'minimist';


import * as fs from 'fs';
import ejs from 'ejs';
import path from 'path';

function generateController(actionName, modulePath) {
    const controllerPath = path.join(modulePath, 'src', 'controller');
    const controllerFile = path.join(controllerPath, `${actionName}_controller.rs`);
    const modFile = path.join(controllerPath, 'mod.rs');

    createFile(
        controllerFile,
        `// ${actionName} controller
pub fn ${actionName}() {
  // TODO: 实现逻辑
}
`
    );
    appendToMod(modFile, `pub mod ${actionName}_controller;`);

    console.log(`Controller 文件已生成: ${controllerFile}`);
}

function generateService(actionName, modulePath) {
    const servicePath = path.join(modulePath, 'src', 'service');
    const serviceFile = path.join(servicePath, `${actionName}_service.rs`);
    const modFile = path.join(servicePath, 'mod.rs');

    createFile(
        serviceFile,
        `// ${actionName} service
pub fn ${actionName}() {
  // TODO: 实现逻辑
}
`
    );
    appendToMod(modFile, `pub mod ${actionName}_service;`);

    console.log(`Service 文件已生成: ${serviceFile}`);
}

function createFile(filePath, content) {
    fs.mkdirSync(path.dirname(filePath), { recursive: true });
    fs.writeFileSync(filePath, content);
}

function appendToMod(modFile, content) {
    if (!fs.existsSync(modFile)) {
        createFile(modFile, '');
    }

    const modContent = fs.readFileSync(modFile, 'utf-8');
    if (!modContent.includes(content)) {
        fs.appendFileSync(modFile, `${content}\n`);
    }
}

export function generateAPIFile(argv_minimist) {
    const genType = argv_minimist.genType;
    const actionName = argv_minimist.actionName;
    const modulePath = argv_minimist.modulePath;

    if (!genType || !actionName || !modulePath) {
        console.error(
            'Usage: node codegen.js <gen-ctl|gen-svc> <action_name> <module_path>'
        );
        process.exit(1);
    }

    switch (genType) {
        case 'gen-ctl':
            generateController(actionName, modulePath);
            generateService(actionName, modulePath);
            break;
        case 'gen-svc':
       
            break;
        default:
            console.error(`不支持的生成类型: ${genType}`);
            process.exit(1);
    }
}
